<?php

declare(strict_types=1);
use Hyperf\HttpServer\Contract\RequestInterface;
if (! function_exists('readFileName')) {
    /**
     * 取出某目录下所有php文件的文件名.
     * @param string $path 文件夹目录
     * @return array 文件名
     */
    function readFileName(string $path): array
    {
        $data = [];
        if (! is_dir($path)) {
            return $data;
        }

        $files = scandir($path);
        foreach ($files as $file) {
            if (in_array($file, ['.', '..', '.DS_Store'])) {
                continue;
            }
            $data[] = preg_replace('/(\w+)\.php/', '$1', $file);
        }
        return $data;
    }
}

if (! function_exists('responseDataFormat')) {
    function responseDataFormat($code, string $message = '', array $data = []): array
    {
        if(empty($message)){
            $message = $code==200?'操作成功':'操作失败';
        }
        return [
            'code' => $code,
            'msg'  => $message,
            'data' => $data,
            "success" => $code==200?"true":"false"
        ];
    }
}

if (! function_exists('isDiRequestInit')) {
    function isDiRequestInit(): bool
    {
        try {
            \Hyperf\Utils\ApplicationContext::getContainer()->get(\Hyperf\HttpServer\Contract\RequestInterface::class)->input('test');
            $res = true;
        } catch (\TypeError $e) {
            $res = false;
        }
        return $res;
    }
}



if (!function_exists('file_full_url')) {
    /**
     * 获取文件完整URL.
     * @param string $path 文件的路径
     * @return string 上传文件的url
     */
    function file_full_url(string $path, string $fileDriver = ''): string
    {
        return \Hyperf\Utils\ApplicationContext::getContainer()->get(Base\Utils\FilesystemExt::class)->getFullUrl($path);
    }
}

if (! function_exists('file_upload_queue')) {
    /**
     * OSS队列上传.
     * @param array $files 例子
     *                     [
     *                     ["URL或本地文件路径", "oss存储路径", "本地路径时，是否删除本地文件，0否1是"],
     *                     ['https://example.com/path/demo.jpg' ,'path/demo.jpg'],
     *                     ['/tmp/path/demo.jpg' ,'path/demo.jpg',],
     *                     ].
     */
    function file_upload_queue(array $files): void
    {
        $asyncFileUpload = make(\App\Common\QueueService\AsyncFileUpload::class);
        if (count($files) <= 10) {
            $asyncFileUpload->upload($files);
            return;
        }

        $newFiles = array_chunk($files, 10);
        foreach ($newFiles as $newFile) {
            $asyncFileUpload->upload($newFile);
        }
    }
}


if (! function_exists('user')) {
    /**
     * @param string $field 字段名称
     * @return array|string 用户信息|用户字段信息
     */
    function user(?string $field = null)
    {
        $RequestInterface = make(RequestInterface::class);
        $resData = $RequestInterface->input('userInfo');
        if (! $resData) {
            return [];
        }
        $field && $resData = $resData[$field];
        return $resData;
    }
}